package com.di.base.proxy;

import io.seata.saga.engine.StateMachineEngine;
import io.seata.saga.proctrl.ProcessContext;
import io.seata.saga.statelang.domain.StateMachineInstance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class OrderSagaService {

    @Autowired
    private StateMachineEngine stateMachineEngine;

    /**
     * 通过Saga状态机创建订单
     * @param userId 用户ID
     * @param productId 商品ID
     * @param count 数量
     * @param amount 金额
     * @return 执行结果
     */
    public Map<String, Object> createOrderSaga(String userId, String productId, Integer count, Double amount) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 构造输入参数
            Map<String, Object> startParams = new HashMap<>();
            startParams.put("userId", userId);
            startParams.put("productId", productId);
            startParams.put("count", count);
            startParams.put("amount", amount);

            log.info("开始执行Saga状态机，创建订单: userId={}, productId={}, count={}, amount={}",
                    userId, productId, count, amount);

            // 同步执行状态机
            StateMachineInstance instance = stateMachineEngine.start("createOrderStateMachine", null, startParams);

            if (instance.getStatus() == io.seata.saga.statelang.domain.ExecutionStatus.SU) {
                log.info("Saga状态机执行成功，订单创建完成");
                result.put("code", 200);
                result.put("message", "订单创建成功");
                result.put("data", instance.getEndParams());
            } else {
                log.error("Saga状态机执行失败，状态: {}", instance.getStatus());
                result.put("code", 500);
                result.put("message", "订单创建失败: " + instance.getException());
                if (instance.getException() != null) {
                    result.put("exception", instance.getException().getMessage());
                }
            }
        } catch (Exception e) {
            log.error("Saga状态机执行异常", e);
            result.put("code", 500);
            result.put("message", "订单创建异常: " + e.getMessage());
        }

        return result;
    }

    /**
     * 异步执行Saga状态机
     * @param userId 用户ID
     * @param productId 商品ID
     * @param count 数量
     * @param amount 金额
     */
    public void createOrderSagaAsync(String userId, String productId, Integer count, Double amount) {
        Map<String, Object> startParams = new HashMap<>();
        startParams.put("userId", userId);
        startParams.put("productId", productId);
        startParams.put("count", count);
        startParams.put("amount", amount);

        log.info("开始异步执行Saga状态机，创建订单: userId={}, productId={}, count={}, amount={}",
                userId, productId, count, amount);

        // 异步执行状态机
        stateMachineEngine.startAsync("createOrderStateMachine", null, startParams, new SagaCallback());
    }

    /**
     * Saga执行回调类
     */
    public static class SagaCallback implements io.seata.saga.engine.AsyncCallback {
        @Override
        public void onFinished(ProcessContext context, StateMachineInstance stateMachineInstance) {
            log.info("Saga状态机异步执行完成，状态: {}", stateMachineInstance.getStatus());
            if (stateMachineInstance.getStatus() == io.seata.saga.statelang.domain.ExecutionStatus.SU) {
                log.info("订单创建成功");
            } else {
                log.error("订单创建失败: {}", stateMachineInstance.getException());
            }
        }

        @Override
        public void onError(ProcessContext context, StateMachineInstance stateMachineInstance, Exception e) {
            log.error("Saga状态机异步执行出错", e);
        }
    }
}